import { Component } from 'react'
import { ScrollView, View, Picker, Image } from '@tarojs/components'
import { observer, inject } from 'mobx-react'
import Taro from '@tarojs/taro'
import { AtActivityIndicator, AtSearchBar, AtIcon } from 'taro-ui'
import { getAreaRange, getAreaIndexByNames,  } from '../../utils/area'
import { getAgeRange, getAgeIndexs, getAgeText, getAgeValueByIndex } from '../../utils/age'
import { getHeightIndexs, getHeightRange, getHeightText, getHeightValueByIndex } from '../../utils/height'

import './index.less'


const AGE_RANGE = getAgeRange({ hasEmpty: true, multiple: true })
const HEIGHT_RANGE = getHeightRange({ hasEmpty: true, multiple: true })

const PAGE_SIZE = 10;

@inject('store')
@observer
class Search extends Component {

  state = {
    loading: false,
    areaRange: [],
    areaValue: [0, 0, 0],
    provinceName: "",
    cityName: "",
    areaName: "",
    ageValue: [0, 0, 0],
    minAge: '',
    maxAge: '',
    heightValue: [0, 0, 0],
    minHeight: null,
    maxHeight: null,
    searchId: "",
    hasMore: true,
    page: 1,
    datasource: [],
    total: -1
  }

  componentDidMount () { 
    this.getAreaRange();
    this.getPageData({ page: 1 });
  }

  getPageData = async ({ page }) => {
    if (this.state.loading) {
      return;
    }
    this.setState({
      loading: true,
    })
    let {
      searchId = '',
      provinceName,
      cityName,
      areaName,
      minAge,
      maxAge,
      minHeight,
      maxHeight,
    } = this.state
    searchId = searchId.replace(/^0+/, '')
    const { success, data } = await Taro.request({
      method: 'post',
      url: '/api/account/search/list',
      data: {
        page,
        pageSize: PAGE_SIZE,
        accountId: searchId ? parseInt(searchId) : null,
        provinceName: provinceName || null,
        cityName: cityName || null,
        areaName: areaName || null,
        minAge: minAge || null,
        maxAge: maxAge || null,
        minHeight: minHeight || null,
        maxHeight: maxHeight || null,
      }
    })
    if (success) {
      const { records, total, pages, current } = data;

      this.setState({
        hasMore: current !== pages,
        page: current,
        total,
        datasource: page === 1 ? records : [...this.state.datasource, ...records],
      })
    }

    this.setState({
      loading: false,
    })
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  onScrollToUpper = (e) => {
    this.setState({
      hasMore: true
    })
    console.log("onScrollToUpper", e);
    this.getPageData({ page: 1 })
  }

  onScroll = (e) => {
    console.log("onScroll", e);
  }

  onScrollToLower = (e) => {
    console.log("onScrollToLower", e);
    if (!this.state.hasMore) {
      return;
    }
    this.getPageData({
      page: this.state.page + 1
    })
  }

  getAreaRange = async () => {
    const resp = await getAreaRange({ hasEmpty: true, value: [] })
    this.setState({
      areaRange: resp.ranges,
      areaValue: [],
    })
  }


  onAreaChange = async (e) => {
    const { value } = e.detail
    const { areaRange } = this.state
    const provinceIndex = value?.[0] || 0;
    const citieIndex = value?.[1] || 0;
    const areaIndex = value?.[2] || 0;
    const provinceName = areaRange?.[0]?.[provinceIndex];
    const cityName = areaRange?.[1]?.[citieIndex];
    const areaName = areaRange?.[2]?.[areaIndex];
    this.setState({
      provinceName: provinceName== '全国' ? '' : provinceName,
      cityName: cityName == '不限' ? '' : cityName,
      areaName: areaName == '不限' ? '' : areaName,
    }, () => {
      this.getPageData({ page: 1 })
    })
  }

  onColumnChange = async (e) => {
    console.log('onColumnChange', 222222, e)
    const { areaValue = [0, 0, 0] } = this.state;
    const { column, value } = e.detail;
    let currentValue = []
    // 省变了
    if (column === 0) {
      currentValue = [value, 0, 0];
    } else if (column === 1) {
      currentValue = [areaValue[0] || 0, value, 0];
    } else {
      currentValue = [areaValue[0] || 0, areaValue[1] || 0, value];
    }
    const resp = await getAreaRange({ hasEmpty: true, value: currentValue })
    this.setState({
      areaRange: resp.ranges,
      areaValue: currentValue,
    })
  }

  onHeightChange = (e) => {
		console.log('onHeightChange:', e);
    const { value } = e.detail;
    const heights =  getHeightValueByIndex({ hasEmpty: true, index: value, multiple: true });
    console.log('heights: ', heights);
    this.setState({
      minHeight: heights[0],
      maxHeight: heights[1]
    }, () => {
      this.getPageData({ page: 1 })
    })
  }

  onSearchIdChange = (searchId) => {
    this.setState({
      searchId
    })
  }

  onSearchId = () => {
    this.getPageData({ page: 1 })
    console.log("searchId:", this.state.searchId, 22222)
  }

  onAgeChange = (e) => {
		console.log('onAgeChange:', e);
    const { value } = e.detail;
    const ages =  getAgeValueByIndex({ hasEmpty: true, index: value, multiple: true });
    console.log('ages: ', ages);
    this.setState({
      minAge: ages[0],
      maxAge: ages[1]
    }, () => {
      this.getPageData({ page: 1 })
    })
  }

  linkToAccountDetail = (item) => {
    Taro.navigateTo({
      url: `/pages/accountDetail/index?id=${item.id}`,
    })
  }

  render () {
    const {
      loading,
      areaRange,
      datasource,
      total,
      provinceName,
      cityName,
      areaName,
      minAge,
      maxAge,
      minHeight,
      maxHeight,
    } = this.state
    console.log(this.state.datasource, 88888)
    const filterWorkText = provinceName ? `${provinceName}${cityName}${areaName}` : '城市'
    const ageText = getAgeText(minAge, maxAge);
    const ageValue = getAgeIndexs({ hasEmpty: true, value: [minAge, maxAge], multiple: true })
    const heightText = getHeightText(minHeight, maxHeight);
    const heightValue = getHeightIndexs({ hasEmpty: true, value: [minHeight, maxHeight], multiple: true });

    return (
      <View className='search-page'>
        <ScrollView
          className='search-page-scroll'
          scrollY
          scrollWithAnimation
          scrollTop={0}
          lowerThreshold={30}
          upperThreshold={30}
          onScrollToUpper={this.onScrollToUpper} // 使用箭头函数的时候 可以这样写 `onScrollToUpper={this.onScrollToUpper}`
          onScrollToLower={this.onScrollToLower}
        >
          <View>
            <AtSearchBar
              className='search-input'
              actionName='搜一下'
              inputType='number'
              placeholder='输入ID搜索'
              value={this.state.searchId}
              onChange={this.onSearchIdChange}
              onActionClick={this.onSearchId}
            />
            <View className='filter'>
              <View className='filter-item'>
                <Picker
                  mode='multiSelector'
                  range={areaRange}
                  value={this.state.areaValue}
                  onChange={this.onAreaChange}
                  onColumnChange={this.onColumnChange}>
                  <View className='filter-item-content'>
                    <View className='filter-item-content-text'>
                      {filterWorkText}
                    </View>
                    <AtIcon value='chevron-down' size='18' color='#666'></AtIcon>
                  </View>
                </Picker>
              </View>
              <View className='filter-item'>
              <Picker
                  mode='multiSelector'
                  range={AGE_RANGE}
                  value={ageValue}
                  onChange={this.onAgeChange}>
                  <View className='filter-item-content'>
                    <View className='filter-item-content-text'>
                      {ageText || '年纪'}
                    </View>
                    <AtIcon value='chevron-down' size='18' color='#666'></AtIcon>
                  </View>
                </Picker>
                {/* <Picker
                  mode='multiSelector'
                  range={AREA_RANGE}
                  value={this.state.ageValue}
                  onChange={this.onAgeChange}>
                  <View className='filter-item-content'>
                    <View className='filter-item-content-text'>
                      {filterWorkText}
                    </View>
                    <AtIcon value='chevron-down' size='18' color='#666'></AtIcon>
                  </View>
                </Picker> */}
              </View>
              <View className='filter-item'>
                <Picker
                  mode='multiSelector'
                  range={HEIGHT_RANGE}
                  value={heightValue}
                  onChange={this.onHeightChange}>
                    <View className='filter-item-content'>
                      <View className='filter-item-content-text'>
                        {heightText || '身高'}
                      </View>
                      <AtIcon value='chevron-down' size='18' color='#666'></AtIcon>
                    </View>
                </Picker>
              </View>
            </View>
              {total == 0 && (
                <View className='empty'>
                  <Image
                    src='../../resource/home-empty.png'
                    mode="aspectFill"
                    className='empty-img'
                  />

                  <View className='empty-text'>暂无数据</View>
                </View>
              )}
              {total > 0 && (
                <View>
                  <View className='card-list'>
                    {datasource.map((item, index) => {
                      const {
                        id,
                        avatar,
                        nickName,
                        occupation,
                        education,
                        birthday,
                        height,
                        homeProvince,
                        homeCity,
                        workAreaCity
                      } = item
                      const year = birthday.slice(0, 4)
                      return (
                        <View className='card-list-item' key={id} onClick={() => {
                          this.linkToAccountDetail(item)
                        }}>
                          <Image
                            className={'card-list-item-avatar'}
                            mode="aspectFill"
                            src={avatar}
                          />
                          <View className='card-list-item-content'>
                            <View className='nickname'>{nickName}</View>
                            <View className='detail'>{year} · {height}cm · {education} · {occupation}</View>
                            <View className='address'>现居{workAreaCity} · {homeProvince}{homeCity}人</View>
                          </View>
                        </View>
                      )
                    })}
                  </View>
                  {loading &&
                    <AtActivityIndicator content='加载中...'></AtActivityIndicator>
                  }
                </View>
              )}
          </View>
        </ScrollView>
      </View>
    )
  }
}

export default Search
